package com.gh.ggkt.activity.service.impl;

import com.atguigu.ggkt.model.activity.CouponInfo;
import com.atguigu.ggkt.model.activity.CouponUse;
import com.atguigu.ggkt.model.user.UserInfo;
import com.atguigu.ggkt.vo.activity.CouponUseQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gh.ggkt.activity.mapper.CouponInfoMapper;
import com.gh.ggkt.activity.remote.UserInfoFeignClient;
import com.gh.ggkt.activity.service.CouponInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gh.ggkt.activity.service.CouponUseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 优惠券信息 服务实现类
 * </p>
 *
 * @author Eric Fang
 * @since 2022-09-18
 */
@Service
public class CouponInfoServiceImpl extends ServiceImpl<CouponInfoMapper, CouponInfo> implements CouponInfoService {

    @Autowired
    private CouponUseService couponUseService;
    @Autowired
    private UserInfoFeignClient userInfoFeignClient;

    @Override
    public IPage<CouponUse> selectCouponUsePage(Page<CouponUse> pageParam, CouponUseQueryVo couponUseQueryVo) {
        Long couponId = couponUseQueryVo.getCouponId();
        String couponStatus = couponUseQueryVo.getCouponStatus();
        String getTimeBegin = couponUseQueryVo.getGetTimeBegin();
        String getTimeEnd = couponUseQueryVo.getGetTimeEnd();
        LambdaQueryWrapper<CouponUse> queryWrapper = new LambdaQueryWrapper<>();
        if (couponId != null) {
            queryWrapper.eq(CouponUse::getCouponId, couponId);
        }
        if (StringUtils.isNotEmpty(couponStatus)) {
            queryWrapper.eq(CouponUse::getCouponStatus, couponStatus);
        }
        if (StringUtils.isNotEmpty(getTimeBegin)) {
            queryWrapper.ge(CouponUse::getGetTime, getTimeBegin);
        }
        if (StringUtils.isNotEmpty(getTimeEnd)) {
            queryWrapper.le(CouponUse::getGetTime, getTimeEnd);
        }
        Page<CouponUse> pageModel = couponUseService.page(pageParam, queryWrapper);
        List<CouponUse> couponUseList = pageModel.getRecords();
        couponUseList.forEach(item -> {
            this.getUserInfoById(item);
        });
        return pageModel;
    }

    private CouponUse getUserInfoById(CouponUse couponUse) {
        Long userId = couponUse.getUserId();
        if (userId != null) {
            UserInfo userInfo = userInfoFeignClient.getById(userId);
            if (userInfo != null) {
                couponUse.getParam().put("nickName", userInfo.getNickName());
                couponUse.getParam().put("phone", userInfo.getPhone());
            }
        }
        return couponUse;
    }
}
